package com.cg.bank.web.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Properties;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class AccessFilter implements Filter {
	private static final String LOGINURI = "/user/login.jsp";
	// 需验证URI列表
	private List<String> accessURIList = new ArrayList<>();
	private String character;

	@Override
	public void init(FilterConfig config) throws ServletException {
		// 载入配置编码
		String character = config.getInitParameter("character");
		if (character == null) {
			this.character = "UTF-8";
		} else {
			this.character = character;
		}
		adddAccessURI();
	}

	/**
	 * 添加需验证的url
	 */
	private void adddAccessURI() {
		// 读取配置文件中需要拦截的文件名
		InputStream in = this.getClass().getClassLoader().getResourceAsStream("../config/filter/accessJsp.properties");
		Properties properties = new Properties();
		try {
			properties.load(in);
			Collection<Object> collection = properties.values();
			for (Object value : collection) {
				accessURIList.add(value.toString());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		// 设置请求编码
		req.setCharacterEncoding(character);

		// 获得请求URI(从Bank2.0/之后开始)
		String requestURI = request.getServletPath();
		// 截取目标url最后后一个"/"出现位置，并进行截取
		String targetURI = requestURI.substring(requestURI.lastIndexOf("/"));
		// 验证需访问页面是否在list中
		if (accessURIList.contains(targetURI)) {
			HttpSession session = request.getSession();
			if (session == null || session.getAttribute("user") == null) {
				// 用户未登录回到login.jsp
				response.sendRedirect(request.getContextPath() + LOGINURI);
				return;
			}
		}

		// 请求下传
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
	}
}